#custom tools
from receipt_saver import util
from receipt_saver import datamodels

import cgi
import os

from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import users

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class LoginPage(webapp.RequestHandler):    
    
    def get(self):
        user = users.get_current_user()
        if user is None:
            self.redirect(users.create_login_url(self.request.uri))
            
        else:
            accnt_query = datamodels.User.gql("WHERE user_id = :1 AND user_email = :2",
                                    user.user_id(), user.email())
            result = accnt_query.get()
            if result is None:
                util.make_account(user.email(), user.user_id())
            else:
                pass  
            
            self.redirect('/receipt')
                      
class ReceiptPage(webapp.RequestHandler):
    def get(self):
        #only runs once
        length = self.numberReceipts()  
        user_account = util.get_accnt(users.get_current_user().email(),
                                      users.get_current_user().user_id())
        labels = [l.tag for l in user_account.user_labels]
        page_filename = 'receipt.html'
        template_values = {'labels': labels,
                           'number_of_receipts': length}
        
        
        self.render(template_values, page_filename)

        db.GqlQuery("")
    
    def post(self):
        """
         - update number of receipts on reload
         - - tests?
         - process receipt fields
        """
        
        user_length = self.numberReceipts()        
        user_account = util.get_accnt(users.get_current_user().email(),
                                      users.get_current_user().user_id())    
        labels = [l.tag for l in user_account.user_labels]
        page_filename = 'receipt.html'
        template_values = {'labels': labels,
                           'actual_number_of_receipts': user_length}
        
        
        
        self.processReceipts(user_length)
        self.render(template_values, page_filename)
        
    def processReceipts(self, quantity):
        """
        !!!
        processes receipt fields
        Number -> Nothing
        side effects: examines each field and stores as many receipts as there are.
            doesn't add receipts with no amount.
        """
        pass
    
    def render(self, template_values, filename):
        """
        !!! NEEEDS TO BE TESTED
        requires: template_values is a dictionary and file indicated by filename exists
        modifies: nothing
        effects: renders webpage with name filename and displays template_values passed
        """
        #renders html file with name filename and passes template_values to rendering engine.
        path = os.path.join(os.path.dirname(__file__), filename)
        self.response.out.write(template.render(path, template_values))
    
    def numberReceipts(self):
        """
        !!! NEEDS TO BE TESTED
        @return: list
        requires: nothing
        modifies: nothing
        effects: produces list with elements from range(length) for use by template engine
        """
        #
        length = self.request.get('input_receipt_number') or 1
        return [(l+1) for l in range(length)]


application = webapp.WSGIApplication([('/', LoginPage),
                                      ('/receipt', ReceiptPage)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
